/// 布局页 * 登录

import { Button, Input, InputPassword } from 'ant-design-vue'
import { ExForm, ExIcon, genComponent } from '@expresso/plus'
import { loginCSS } from './styles'
import { type LoginParams, apiLogin, apiLoginInfo } from '@/apis/Login'
import { cache, isSucceed } from '@/helpers'
import { useLoginStore, useMenusStore } from '@/stores'

/**
 * 登录
 */
export default genComponent({ name: 'Login' }, () => {
  //# 成员

  /** 加载器 */
  const loading = useLoading('local')

  /** 路由 */
  const router = useRouter()

  //// 全局状态 ////

  /** 全局状态-菜单 */
  const menus = useMenusStore()
  //|
  /** 全局状态-登录 */
  const login = useLoginStore()

  //// 表单 ////

  /** 获取随机报文 */
  function generateRandomMessage(): string {
    let result = ''
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    const charactersLength = characters.length
    for (let i = 0; i < 10; i++) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength))
    }
    return result
  }

  /** 表单 */
  const form = useForm<LoginParams>()

  /** 表单 登录 */
  const onLogin = async () => {
    try {
      await form.api!.validateFields()
      loading(async () => {
        const data = form.getData(true)

        if (!cache.getToken()) {
          const res = await apiLogin(data)
          if (isSucceed(res, false)) {
            const { accessToken, refreshToken } = res.data
            cache.setToken({ accessToken, refreshToken })
            /** 添加登录ws标识 */
            sessionStorage.setItem('uuid', generateRandomMessage())
          }
          else {
            return
          }
        }

        const loginInfo = await apiLoginInfo()
        if (loginInfo) {
          cache.setLoginInfo(loginInfo)
          router.push('/home')
        }
      })
    }
    catch { }
  }

  //# 周期

  onMounted(() => {
    menus.resetMenus()
    cache.clear()
    login.resetProject()
  })

  return () => (
    <div class={['login', loginCSS]}>
      <header>
        <div class="title">
          <ExIcon type="hd-icon-shouye" size={28} />
          交付平台
        </div>
      </header>
      <main>
        <figure></figure>
        <section
          onKeydown={(evt) => {
            if (evt.key === 'Enter') {
              onLogin()
            }
          }}
        >
          <div class="login-panel">
            {/* 登录徽标 */}
            <div class="login-logo" />

            {/* 登录表单 */}
            <ExForm class="login-form" {...form.bind} labelType="placeholder" layout="vertical">
              <ExForm.Item label="用户名" name="username" rule={rule()}>
                <Input prefix={<div class="label username"></div>} />
              </ExForm.Item>
              <ExForm.Item label="密码" name="password" rule={rule()}>
                <InputPassword prefix={<div class="label password"></div>}>
                  {{
                    iconRender: (visible: boolean) => {
                      return (
                        <div style={{ cursor: 'pointer' }}>
                          <ExIcon type="hd-icon-yanjing" class={{ visible }} size={18} />
                        </div>
                      )
                    },
                  }}
                </InputPassword>
              </ExForm.Item>
            </ExForm>
            {/* 登录按钮 */}
            <Button class="login-btn" type="primary" onClick={onLogin} loading={loading.value}>
              登录
            </Button>
          </div>
        </section>
      </main>
      <footer>Copyright © 2024 天津华德智慧科技集团有限公司 版权所有 津ICP备16006426号-3</footer>
    </div>
  )
})
